package prototech.ahedra.action;

import java.io.File;

import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import prototech.ahedra.form.UploadForm;
import prototech.ahedra.br.ProcessUpload;

public class UploadAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String status = null;

		UploadForm uploadForm = (UploadForm) form;
		FileOutputStream outputStream = null;
		FormFile formFile = null;
		try {
			formFile = uploadForm.getFile();
			// String path = getServlet().getServletContext().getRealPath("") +
			// "/" + formFile.getFileName();
			String path = "c:/temp/uploaded/" + request.getSession().getId()
					+ "_" + formFile.getFileName();
			outputStream = new FileOutputStream(new File(path));
			outputStream.write(formFile.getFileData());

			ProcessUpload.ProcessFile(path);

			status = "success";
		} catch (Exception ex) {
			status = "fail";
			throw ex;
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		return mapping.findForward(status);
	}
}
